package club.babyf.nativeai.demo.algorithm;

/**
 * LongestPalindrome.
 *
 * @author zhanglei.
 * @date 2025/4/22 18:00.
 * @description 最长回文子串.
 */
public class _4_LongestPalindrome {

    public String longestPalindrome(String s) {
        if (s == null || s.isEmpty()) {
            return "";
        }

        int start = 0;
        int end = 0;

        for (int i = 0; i < s.length(); i++) {
            int len1 = expandAroundCenter(i, i, s);
            int len2 = expandAroundCenter(i, i + 1, s);
            int max = Math.max(len1, len2);
            if (max > end - start) {
                start = i - (max - 1) / 2;
                end = i + max / 2;
            }
        }

        return s.substring(start, end + 1);
    }

    private int expandAroundCenter(int left, int right, String s) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }

    public static void main(String[] args) {
        _4_LongestPalindrome longestPalindrome = new _4_LongestPalindrome();
        String s = longestPalindrome.longestPalindrome("babad");
        System.out.println(s);
    }

}
